import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';

import { Form } from '@ant-design/compatible';
import {
  Card,
  Col,
  Input,
  Row,
  DatePicker,
  Table,
  Button,
} from 'antd';
import '@ant-design/compatible/assets/index.css';

const { RangePicker } = DatePicker;
const { Item } = Form;
interface BorrowingInfoProps {
  detail?: object | any;
  reimbursement?: object | any;
  forms: any;
  fetchAction: (typeName: string, payload: any) => void;
  mergeFun: any;
  saleInfo?: any;
}

interface BorrowingInfoState {
  repayment_list: any;
  pageNum: number;
  pageCount: number;
}

function mapStateToProps(state: any) {
  const {
    franchiseeContractEditor: { detail, reimbursement, saleInfo },
  } = state;

  return {
    detail,
    reimbursement,
    saleInfo,
  };
}

@connect(mapStateToProps)

class BorrowingInfoElem extends Component<BorrowingInfoProps, BorrowingInfoState> {
  state: BorrowingInfoState = {
    repayment_list: [],
    pageNum: 1,
    pageCount: 10,
  }

  static getDerivedStateFromProps(nextProps: BorrowingInfoProps, preState: BorrowingInfoState) {
    const { detail, reimbursement } = nextProps;

    if ((detail.repayment_list || reimbursement.repayment_list)) {
      const new_repayment_list = reimbursement.repayment_list
        || detail.repayment_list.map((item: any) => (
          {
            ...item,
            amount: item.amount / 100,
            interest: item.interest / 100,
            principal: item.principal / 100,
            residual_principal: item.residual_principal / 100,
          }
        ));

      const repayment_list = [
        {
          period_num: '合计',
          amount: reimbursement.total_amount
            || detail.repayment_list.reduce((origin: any, target: any) => (
              origin + target.amount
            ), 0) / 100,
          principal: reimbursement.total_principal
            || detail.repayment_list.reduce((origin: any, target: any) => (
              origin + target.principal
            ), 0) / 100,
          interest: reimbursement.total_interest
            || detail.repayment_list.reduce((origin: any, target: any) => (
              origin + target.interest
            ), 0) / 100,
        },
        ...new_repayment_list,
      ];

      return {
        repayment_list,
      };
    }

    return null;
  }

  getMonthLenth = (start_time: string, end_time: string) => {
    const between = new Date(end_time).getTime() - new Date(start_time).getTime();
    return Math.floor(between / 1000 / 60 / 60 / 24 / 30);
  }

  // 生成还款明细
  handleCreateDetail = () => {
    const { forms: { getFieldsValue } } = this.props;

    const returnValues = getFieldsValue(['momentTime', 'loan_amount', 'annual_interest_rate']);
    const start_time = moment(returnValues.momentTime[0]).format('YYYY-MM-DD');
    const end_time = moment(returnValues.momentTime[1]).format('YYYY-MM-DD');
    const repayment_count = this.getMonthLenth(start_time, end_time);

    const { mergeFun } = this.props;
    mergeFun('repayment_count', repayment_count);
    const params = {
      repayment_count,
      loan_amount: returnValues.loan_amount * 100,
      annual_interest_rate: returnValues.annual_interest_rate,
    };

    const { fetchAction } = this.props;
    fetchAction('fetchReimbursement', params);
  }

  // 改变页码
  handleChangePage = (pageInfo: any) => this.setState({ pageNum: pageInfo.current });

  renderBorrowingInfoELem = () => {
    const {
      detail,
      forms: { getFieldDecorator },
      saleInfo,
    } = this.props;

    let total: number | string = 0;

    if (detail.sale_total_amount) {
      total = (detail.sale_total_amount / 100).toFixed(2);
    } else if (saleInfo.total_amount) {
      total = (saleInfo.total_amount / 100).toFixed(2);
    } else total = 0;

    return (
      <Card title="借贷信息" bordered={false}>
        <div className="subtitle marginB16">销售总额：{total}元</div>
        <Row gutter={12}>
          <Col md={8} sm={24}>
            <Item label="首付金额" colon={false}>
              {getFieldDecorator('down_payment', {
                initialValue: detail.down_payment && (detail.down_payment / 100).toFixed(2),
                rules: [{ required: true, message: '请输入首付金额' }],
              })(
                <Input
                  allowClear
                  type="number"
                  addonAfter="元"
                  placeholder="请输入"
                />,
              )}
            </Item>
          </Col>
          <Col md={8} sm={24}>
            <Item label="借款金额">
              {getFieldDecorator('loan_amount', {
                initialValue: detail.loan_amount && (detail.loan_amount / 100).toFixed(2),
                rules: [{ required: true, message: '请输入借款金额' }],
              })(
                <Input
                  allowClear
                  type="number"
                  addonAfter="元"
                  placeholder="请输入"
                />,
              )}
            </Item>
          </Col>
          <Col md={8} sm={24}>
            <Item label="　年利率" colon={false}>
              {getFieldDecorator('annual_interest_rate', {
                initialValue: detail.annual_interest_rate,
                rules: [{ required: true, message: '请输入年利率' }],
              })(
                <Input
                  allowClear
                  type="number"
                  addonAfter="%"
                  placeholder="请输入"
                />,
              )}
            </Item>
          </Col>
        </Row>
        <Row gutter={12}>
          <Col md={8} sm={24}>
            <Item label="借款期限" colon={false}>
              {getFieldDecorator('momentTime', {
                initialValue: detail.start_time && [
                  moment(detail.start_time.split(' --- ')[0], 'YYYY-MM-DD'),
                  moment(detail.start_time.split(' --- ')[1], 'YYYY-MM-DD'),
                ],
                rules: [{ required: true, message: '请选择借款期限' }],
              })(<RangePicker format="YYYY-MM-DD" />)}
            </Item>
          </Col>
          <Col md={8} sm={24}>
            <Button
              type="primary"
              onClick={this.handleCreateDetail}
            >
              生成还款明细
            </Button>
          </Col>
        </Row>
        {this.renderNperList()}
      </Card>
    );
  };

  renderNperList = () => {
    const columns = [
      {
        title: '期数',
        dataIndex: 'period_num',
      },
      {
        title: '当期还款额',
        dataIndex: 'amount',
      },
      {
        title: '当期还款本金',
        dataIndex: 'principal',
      },
      {
        title: '当期还款利息',
        dataIndex: 'interest',
      },
      {
        title: '剩余本金',
        dataIndex: 'residual_principal',
      },
    ];

    const {
      repayment_list,
      repayment_list: { length },
      pageNum: current,
      pageCount: pageSize,
    } = this.state;

    const Pagination = {
      current,
      pageSize,
      total: length,
    };

    return (
      <Table
        className="marginT24 tableList statementTable"
        rowKey="period_num"
        columns={columns}
        pagination={length ? Pagination : false}
        dataSource={repayment_list}
        onChange={this.handleChangePage}
      />
    );
  };

  render() {
    return (
      <Fragment>
        {this.renderBorrowingInfoELem()}
      </Fragment>
    );
  }
}

export default BorrowingInfoElem;
